package com.fz.study.project.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.fz.study.project.entity.Blog;
import com.fz.study.project.entity.Result;
import com.fz.study.project.entity.dto.UserDTO;
import com.fz.study.project.exception.BizException;
import com.fz.study.project.mapper.TbBlogMapper;
import com.fz.study.project.service.ITbBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fz.study.project.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-04
 */
@RequiredArgsConstructor
@Service
public class BlogServiceImpl extends ServiceImpl<TbBlogMapper, Blog> implements ITbBlogService {

    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public Result likeBlog(Long id) {
//        判断用户是否登录
        Long userId = UserHolder.getUser().getId();
        if (userId == null){
            BizException.throwBizException("用户未登录不允许点赞！");
        }
//        判断用户是否已经点过赞
        String key = "blog:liked:" + id;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if (BooleanUtil.isFalse(isMember)){
            //        未点赞就点赞
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                //            redis中加入用户信息
                stringRedisTemplate.opsForZSet().add(key,userId.toString(), System.currentTimeMillis());
            }
        }else {
//        已点赞就取消点赞
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
//            redis中删除用户信息
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.success("成功！");
    }
}
